import React, { useRef, useEffect } from "react";
import { dataSource } from "../constants/data";
import Smap from "./sport-map";
import SportStyle from "./sport.module.css";
import { useNavigate } from "react-router-dom";

export default function SportMap() {
  let Navigate = useNavigate();
  const videoRefs = useRef([]);
  const lineRef = useRef(null);

  const handleScroll = () => {
    const { top, bottom } = lineRef.current.getBoundingClientRect();

    // 遍历所有视频元素，如果在红线内则播放视频，否则停止播放
    videoRefs.current.forEach((video) => {
      const { top: videoTop, bottom: videoBottom } =
        video.getBoundingClientRect();
      if (videoTop <= bottom && videoBottom >= top) {
        video.play(); // 在红线范围内则播放视频
      } else {
        video.pause(); // 不在红线范围内则暂停视频
      }
    });
  };

  useEffect(() => {
    // 监听滚动事件，每次滚动都更新视频播放状态
    window.addEventListener("scroll", handleScroll);

    // 组件卸载时清除监听事件
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  return (
    <div>
      <p
        onClick={() => {
          Navigate("/sport");
        }}
      >
        返回
      </p>
      <nav>导航</nav>
      <div>
        <Smap></Smap>
      </div>

      <h3>跑步课程</h3>
      <div className={SportStyle.videolist}>
        {dataSource.hot.list.map((item, index) => (
          <div key={index}>
            <video
              src={item.src}
              width="170px"
              height="350"
              style={{
                objectFit: "cover",
                borderRadius: "6px",
                margin: "10px",
              }}
              ref={(el) => (videoRefs.current[index] = el)} // 在 ref 中保存视频元素的引用
            ></video>
          </div>
        ))}
      </div>

      {/* 在 line 元素中保存 ref */}
      <div className={SportStyle.line} ref={lineRef}></div>
    </div>
  );
}
